package com.jokesoft.supermanager.core.repositories;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.jokesoft.supermanager.common.services.Address;
import com.jokesoft.supermanager.core.entities.AddressEntity;
import com.jokesoft.supermanager.core.entities.PersonEntity;

@Repository
public class PersonRepositoryImpl implements PersonRepository {

    private static final Logger LOGGER = LoggerFactory.getLogger(PersonRepositoryImpl.class);

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @Transactional
    public PersonEntity insertPerson(String firstName, String lastName, String role, List<Address> addressList) {

        PersonEntity person = new PersonEntity();

        person.setFirstName(firstName);
        person.setLastName(lastName);
        person.setRole(role);
        this.entityManager.persist(person);

        for (Address address : addressList) {
            AddressEntity addresEntity = new AddressEntity();
            addresEntity.setStreet(address.getStreet());
            addresEntity.setPostalCode(address.getPostalCode());
            addresEntity.setPostOffice(address.getPostOffice());
            addresEntity.setCountry(address.getCountry());
            addresEntity.setPersonEntity(person);
            person.getAddressList().add(addresEntity);
            this.entityManager.persist(addresEntity);
        }

        LOGGER.debug("Inserting person {}", person);

        return person;
    }

    @Override
    public PersonEntity findById(String id) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void delete(String id) {
        // TODO Auto-generated method stub

    }

    @Override
    public List<PersonEntity> fetchAllPersons() {
        TypedQuery<PersonEntity> q = entityManager.createNamedQuery(PersonEntity.FETCH_ALL, PersonEntity.class);
        return q.getResultList();
    }

}
